// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "mainwindow.h"
#include "ui_mainwindow.h"

// 引入必要的Qt模块
#include <QtCore/QDateTime>
#include <QtMqtt/QMqttClient>
#include <QtWidgets/QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 初始化MQTT客户端
    m_client = new QMqttClient(this);

    // 从UI控件读取初始主机地址和端口号
    m_client->setHostname(ui->lineEditHost->text());
    m_client->setPort(static_cast<quint16>(ui->spinBoxPort->value()));

    // 连接状态变化信号与日志记录槽
    connect(m_client, &QMqttClient::stateChanged, this, &MainWindow::updateLogStateChange);

    // 连接断开信号与UI重置槽
    connect(m_client, &QMqttClient::disconnected, this, &MainWindow::brokerDisconnected);

    // 消息接收处理：将消息内容格式化后显示在日志框
    connect(m_client, &QMqttClient::messageReceived, this, [this](const QByteArray &message, const QMqttTopicName &topic) {
        const QString content = QDateTime::currentDateTime().toString()
                    + QLatin1String(" Received Topic: ")
                    + topic.name()
                    + QLatin1String(" Message: ")
                    + message
                    + QLatin1Char('\n');

        // 输出到日志框
        if (!content.isEmpty()) {
            // 如果超过最大刷新次数，清空日志
            if (mainwindow_logRefreshCount >= MainWindow_MAX_REFRESH_COUNT)
            {
                ui->editLog->clear();
                mainwindow_logRefreshCount = 0; // 重置计数器
            }
            ui->editLog->insertPlainText(content);
            mainwindow_logRefreshCount++;       // 递增计数器
        }

        // 触发信号
        emit messageReceived(content, topic.name());
    });

    // 服务器心跳响应处理：记录Ping响应时间
    connect(m_client, &QMqttClient::pingResponseReceived, this, [this]() {
        const QString content = QDateTime::currentDateTime().toString()
                    + QLatin1String(" PingResponse")
                    + QLatin1Char('\n');
        ui->editLog->insertPlainText(content);
    });

    // 实时更新主机地址和端口设置
    connect(ui->lineEditHost, &QLineEdit::textChanged, m_client, &QMqttClient::setHostname);
    connect(ui->spinBoxPort, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::setClientPort);
    // 连接按钮点击信号与槽
    connect(ui->buttonConnect, &QPushButton::clicked, this, &MainWindow::main_buttonConnect_clicked);
    // 退出按钮点击信号与槽
    connect(ui->buttonQuit, &QPushButton::clicked, this, &MainWindow::main_buttonQuit_clicked);
    // 发布消息按钮点击信号与槽
    connect(ui->buttonPublish, &QPushButton::clicked, this, &MainWindow::main_buttonPublish_clicked);
    // 订阅主题按钮点击信号与槽
    connect(ui->buttonSubscribe, &QPushButton::clicked, this, &MainWindow::main_buttonSubscribe_clicked);
    // 初始化时记录初始状态
    updateLogStateChange();
}

MainWindow::~MainWindow()
{
    delete ui; // 清理UI资源
}

// 连接/断开按钮点击处理
void MainWindow::main_buttonConnect_clicked()
{

    if (m_client->state() == QMqttClient::Disconnected)
    {
        // 连接时禁用输入控件，更新按钮文字
        ui->lineEditHost->setEnabled(false);
        ui->spinBoxPort->setEnabled(false);
        ui->buttonConnect->setText(tr("断开连接"));
        m_client->connectToHost();
    } 
    else 
    {
        // 断开时恢复输入控件，重置按钮文字
        ui->lineEditHost->setEnabled(true);
        ui->spinBoxPort->setEnabled(true);
        ui->buttonConnect->setText(tr("连接"));
        m_client->disconnectFromHost();
    }
}

// 退出按钮点击处理
void MainWindow::main_buttonQuit_clicked()
{
    QApplication::quit(); // 退出应用程序
}

// 状态变化日志记录
void MainWindow::updateLogStateChange()
{
    const QString content = QDateTime::currentDateTime().toString()
                    + QLatin1String(": State Change")
                    + QString::number(m_client->state())
                    + QLatin1Char('\n');
    ui->editLog->insertPlainText(content);
}

// 服务器断开后的UI重置
void MainWindow::brokerDisconnected()
{
    ui->lineEditHost->setEnabled(true);
    ui->spinBoxPort->setEnabled(true);
    ui->buttonConnect->setText(tr("连接")); // 恢复连接按钮状态
}

// 端口设置方法（适配QSpinBox的int类型）
void MainWindow::setClientPort(int p)
{
    m_client->setPort(static_cast<quint16>(p));
}

// 发布消息按钮处理
void MainWindow::main_buttonPublish_clicked()
{
    // 尝试发布消息，失败时显示错误对话框
    if (m_client->publish(ui->lineEditTopic->text(), ui->lineEditMessage->text().toUtf8()) == -1)
        QMessageBox::critical(this, QLatin1String("Error"), QLatin1String("Could not publish message"));
}

// 订阅主题按钮处理
void MainWindow::main_buttonSubscribe_clicked()
{
    auto subscription = m_client->subscribe(ui->lineEditTopic->text(), 1);
    if (!subscription) {
        // 订阅失败时提示错误（通常因为未连接）
        QMessageBox::critical(this, QLatin1String("Error"), QLatin1String("Could not subscribe. Is there a valid connection?"));
        return;
    }
}

// 温湿度监测面板按钮处理
void MainWindow::on_Monitoring_Panel_Button_clicked()
{
    datashow *c = new datashow;
    c->setAttribute(Qt::WA_DeleteOnClose);
    connect(this, &MainWindow::messageReceived, c, &datashow::displayMessage);

    // 设置统计间隔（例如每XX秒统计一次）
    c->setStatInterval(20);

    c->show(); // 界面显示
}

// 错误日志按钮处理
void MainWindow::LoggingButton_clicked()
{

}


